<?php


namespace backend\modules\tool\Job;


use backend\modules\tool\DataSource\DataAdapter;
use backend\modules\tool\DataSource\Log\DataBaseBackHelper;
use backend\modules\tool\DataSource\Log\Log;
use backend\modules\tool\helpers\Context;
use backend\modules\tool\helpers\FileHelper;
use backend\modules\tool\models\DataBaseBack;
use backend\modules\tool\models\DataSourceTask;
use backend\modules\tool\models\SqlConfig;
use yii\db\Exception;

class DataBaseBackNode extends DataAdapter
{
    /**
     * @var SqlConfig $source_databse
     */
    protected $source_databse=null;
    protected $node_id=null;
    protected $log;
    public function __construct($id)
    {
        $this->id=$id;
        $task=DataSourceTask::find()->where(["id"=>$id])->one();
        $this->log=Context::SingleTon()->getLog();
        $task_id=$task->task_id;
        $node=DataBaseBack::find()->andWhere(["id"=>$task_id])->one();
        $this->node_id=$task_id;
        SqlConfig::GetConfigPdo($node->source_database);
        $this->source_database=SqlConfig::find()->andWhere(["id"=>$node->source_database])->one();
        $this->log=DataBaseBack::getLog($this->node_id);
    }

    public function StoreData($data)
    {

    }
    public function DataSource()
    {
        $helper=DataBaseBackHelper::SingleTon($this->node_id);
        $info=$helper->computeShell($this->source_database);
        $shell=$info["shell"];
        $process_info=shell_exec($shell);
        $path=$info["path"];
        if(is_file($path)) {
            $this->log->write("数据备份成功====>{$path}}");
            $this->log->write("文件大小====>".$this->getSize(filesize($path)));
            $path_list=FileHelper::FileWalk(dirname($path));
            foreach ($path_list as $value){
                if(filemtime($value)<strtotime("-7 day")){
                    unlink($value);
                    $this->log->write("过期备份已被删除====>{$value}");
                }
            }
        }
        $this->log->write("运行日志:".PHP_EOL.$process_info);
    }
    public function HandleData($data)
    {

    }
    public function run()
    {
        parent::run(); // TODO: Change the autogenerated stub
    }
    public function getSize($filesize) {
        if($filesize >= 1073741824) {
            $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';

        } elseif($filesize >= 1048576) {
            $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';

        } elseif($filesize >= 1024) {
            $filesize = round($filesize / 1024 * 100) / 100 . ' KB';

        } else {
            $filesize = $filesize . ' Byte';

        }

        return $filesize;

    }
}